namespace Xmef.Library
{
    using System.Threading;

    public abstract class WorkItemContainer<T> : PluginIdentity
    {
        protected static WorkItemContainer<T> Current;
        protected static object SyncRoot;
        private T _item;

        static WorkItemContainer()
        {
            SyncRoot = new object();
        }

        protected WorkItemContainer(T item)
        {
            this._item = item;
        }

        public T GetWorkItem()
        {
            return this._item;
        }

        protected abstract void Start();
        
        protected abstract void Process();
        
        protected abstract void Stop();
        
        public static void QueryAsync(WorkItemContainer<T> item)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(item.Run), item);
        }
        
        public static void QuerySync(WorkItemContainer<T> item)
        {
            item.Run(item);
        }

        protected virtual void Run(object value)
        {
            WorkItemContainer<T> item = value as WorkItemContainer<T>;
            if (item != null)
            {
                item.Start();
                item.Process();
                item.Stop();
            }
        }

        public WorkItemContainer<T> Link
        {
            get;
            set;
        }

        public void SetWorkItem(T value)
        {
            this._item = value;
        }
    }
}

